package cn.support.neo.mvp.core.helper;

import android.net.ParseException;

import com.google.gson.JsonParseException;

import org.json.JSONException;

import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import cn.support.neo.mvp.model.qualifier.ResultCode;
import cn.support.neo.mvp.core.base.ResultException;
import retrofit2.HttpException;


/**
 * <b>Name:</b>错误掌控处理者<br>
 * <b>Author:</b> WK（wangkun@xjzhicheng.com)<br>
 * <b>Date:</b> 2017-01-17<br>
 * <b>Describe:</b> PLEASE TO FIXME...<br>
 * <b>Version:</b>V1.0<br>
 * <b>Revision History:</b><br>
 */
public class ExceptionHandler {

    private static final int UNAUTHORIZED = 401;
    private static final int FORBIDDEN = 403;
    private static final int NOT_FOUND = 404;
    private static final int REQUEST_TIMEOUT = 408;
    private static final int INTERNAL_SERVER_ERROR = 500;
    private static final int BAD_GATEWAY = 502;
    private static final int SERVICE_UNAVAILABLE = 503;
    private static final int GATEWAY_TIMEOUT = 504;

    public static ResultException handleException(Throwable e) {
        if(e instanceof ResultException){
            return (ResultException) e;
        }

        ResultException ex;
        if (e instanceof HttpException) {
            HttpException httpException = (HttpException) e;
            ex = new ResultException(ResultCode.HTTP, httpException.getMessage());
            switch (httpException.code()) {
                case GATEWAY_TIMEOUT:
                    ex = new ResultException(ResultCode.NETWORK, "连接超时，请检查网络是否连接！");
                    break;
                case NOT_FOUND:
                case REQUEST_TIMEOUT:
                case INTERNAL_SERVER_ERROR:
                case UNAUTHORIZED:
                case FORBIDDEN:
                case BAD_GATEWAY:
                case SERVICE_UNAVAILABLE:
                default:
                    //HTTP网络错误
                    ex = new ResultException(ResultCode.HTTP, "HTTP网络错误");
                    break;
            }
            return ex;
        } else if (e instanceof JsonParseException
                || e instanceof JSONException
                || e instanceof ParseException) {
            ex = new ResultException(ResultCode.CONVERSION, "Json解析错误");
            return ex;
        } else if (e instanceof ConnectException
                || e instanceof SocketTimeoutException
                || e instanceof UnknownHostException) {
            ex = new ResultException(ResultCode.NETWORK, "检查网络是否连接");
            return ex;
        } else if (e instanceof javax.net.ssl.SSLHandshakeException) {
            ex = new ResultException(ResultCode.SSL_ERROR, "证书验证失败");
            return ex;
        } else {
            ex = new ResultException(ResultCode.UNKNOWN, "未知错误");
            return ex;
        }
    }
}
